import { http } from '@/utils/http'
const DICT_CACHE_KEY = 'UNI_APP_DICT_V1' // 使用版本号避免旧缓存污染
const DICT_EXPIRE_TIME = 24 * 60 * 60 * 1000 // 缓存 24 小时

/**
 *  console.log(await getDictAllData("config_type"))
 */
export const getDictAllData = async (type: string) => {
  // 1. 读取缓存
  const cached = uni.getStorageSync(DICT_CACHE_KEY)
  if (cached && cached.expire > Date.now()) {
    return cached.data.find((item: any) => item.dictType === type).dataList
  }
  // 2. 获取数据
  const res = await http({
    method: 'GET',
    url: `/sys/webchat/dict/all`,
    data: {},
  })
  const dictList: any[] = res.data
  // 3. 更新缓存
  uni.setStorageSync(DICT_CACHE_KEY, {
    data: dictList,
    expire: Date.now() + DICT_EXPIRE_TIME,
  })
  return dictList
}

export const clearDictCache = () => {
  uni.removeStorageSync(DICT_CACHE_KEY)
}

export const getDictLabel = (points_source_type_data: any[], val: number | string) => {
  // await getDictAllData("points_source_type")
  return points_source_type_data.find((item: any) => String(item.dictValue) === String(val))
    .dictLabel
}
